<template>
  <div class="app-container charts" v-loading="loading">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="70px" :rules="rules">
                          <el-form-item label="设备类型" prop="machineTypeId">
                            <el-select v-model="queryParams.machineTypeId" placeholder="请选择制造类型" clearable style="width: 150px">
                                <el-option
                                        v-for="dict in machineTypeIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                          </el-form-item>
                          <el-form-item label="日期基准" prop="endTime">
                            <WeekTimePicker type="date" v-model="queryParams.dataTime" style="width: 150px"/>
                            <el-button style="margin-left: 10px;" type="primary" icon="Search" @click="getData">查询</el-button>
                        </el-form-item>
    </el-form>
    <div id="chart_line" style="width: 100%; height: 300px;" v-show="isShow"></div>

    <t-ag-grid
      v-show="isShow"
      style="height: 163px;"
      :column-defs="column"
      :row-data="tableData"
      :row-buffer="20"
      align="center"
      :defaultColDef = "{
          suppressMenu:true
      }"
      header-align="center"
      />
      <!-- @cell-clicked="onCellClicked" -->

    <div id="chart_heatMap" style="width: 100%; height: 500px; margin-top: 20px;" v-show="isShow"></div>
  </div>
</template>

<script setup name="GroupAST">
  import { listHeatMap } from "@/api/indexAnalyse/groupAST"
  import { heatMapOptions } from './heatMap'
  import { lineOptions } from './line'
  import { getTableColumns } from "./table"
  const { proxy } = getCurrentInstance()
  import moment from 'moment'
  import * as echarts from 'echarts'

  import { useRouter } from 'vue-router'
  const router = useRouter()

  const queryParams = reactive({
    machineTypeId: '叠瓦线',
    dataTime: moment().subtract(1, 'days').format('YYYY-MM-DD')
  })
  const loading = ref(false)

  const machineTypeIdOptions = ref([
    { label: 'MBB线', value: 'MBB线' },
    { label: '叠瓦线', value: '叠瓦线' }
    // { label: 'ACF线', value: 'ACF线' }
  ])

  onActivated(() => {
    let { machineTypeId, dataTime } = history?.state
    if(machineTypeId && dataTime){
      queryParams.machineTypeId = machineTypeId
      queryParams.dataTime = dataTime
      getData()
    }
  })

  const rules = {
    machineTypeId: [
      { required: true, message: "制造类型不能为空", trigger: "change" }
    ]
  }

  const column = ref([])
  const tableData = ref([])

  const isShow = ref(false)

  // 基于准备好的dom，初始化echarts实例
  let lineChart = null
  let heatMapChart = null

  onMounted(() => {
    lineChart = echarts.getInstanceByDom(document.getElementById("chart_line"))
    heatMapChart = echarts.getInstanceByDom(document.getElementById("chart_heatMap"))

    const resizeObserver = new ResizeObserver((entries, b) => {
      if(lineChart){
        lineChart.resize()
      }
      if(heatMapChart){
        heatMapChart.resize()
      }
    })
    resizeObserver.observe(document.getElementById("chart_line"))
    resizeObserver.observe(document.getElementById("chart_heatMap"))

    if(!lineChart){
      lineChart = echarts.init(document.getElementById("chart_line"))
    }
    if (!heatMapChart) {
      heatMapChart = echarts.init(document.getElementById("chart_heatMap"))
    }

  })

  const getData = () => {

    proxy.$refs.queryRef.validate(valid => { // 表单校验
      if (valid) {
        loading.value = true
        queryParams.dataTime = moment(queryParams.dataTime).format('YYYY-MM-DD')
        listHeatMap(queryParams).then((res) => {
          loading.value = false
          if(res.rows[0].heatMapAvgList.length || res.rows[0].heatMapDetailList.length){ // 返回数据时显示
            isShow.value = true

            const { heatMapAvgList, heatMapDetailList, baseTT } = res.rows[0]
            const { lineOption } = lineOptions(heatMapAvgList, queryParams.machineTypeId, moment(queryParams.dataTime).format('MM-DD'))
            lineChart.setOption(lineOption)

            const { columns,  target } = getTableColumns(heatMapAvgList)
            column.value = columns
            tableData.value = target

            column.value.forEach((item) => {
              item.cellStyle = cellStyle
            })

            const { heatMapOption } = heatMapOptions(heatMapDetailList, Number(baseTT)/* 参考值 */)
            heatMapChart.setOption(heatMapOption)
          } else {
            isShow.value = false
          }
        })

      }
    })

    heatMapChart.on('click', function(params) {
      if(params.componentType === 'yAxis'){
        router.push({
          path: '/indexAnalyse/astAnalysis/machineAST',
          state: {
            machineTypeId: queryParams.machineTypeId,
            mainLineName: `H05-${params.value}`,
            dataTime: queryParams.dataTime
          }
        })
      } else if(params.componentType === 'xAxis') {
        router.push({
          path: '/indexAnalyse/astAnalysis/singleDayAST',
          query: {
            machineTypeId: queryParams.machineTypeId,
            dataTime: `${queryParams.dataTime.substr(0, 4)}-${params.value}`
          }
        })
      }
    })
  }

  const cellStyle = ({ data,  value }) => {
    if(data.MBB === '差异' && value > 0 ){
      return {
        color: 'red',
        fontWeight: 'bold'
      }
    }
  }

</script>

<style lang="less" scoped>
.charts {
  overflow-x: scroll;
}
</style>